package cn.tuling.config;

import cn.tuling.mybatis.MybatisBeanDefinitionScanner;
import cn.tuling.mybatis.MybatisFactoryBean;
import cn.tuling.mybatis.MybatisMapperScan;
import cn.tuling.mybatis.mapper.OrderMapper;
import cn.tuling.mybatis.mapper.UserMapper;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;
import java.util.Map;


public class MyImportBeanDefinitionRegistry implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        // 扫描路径
        Map<String, Object> mybatisMapperScan = importingClassMetadata.getAnnotationAttributes(MybatisMapperScan.class.getName());
        String path = ((String) mybatisMapperScan.get("value"));

        MybatisBeanDefinitionScanner scanner = new MybatisBeanDefinitionScanner(registry);
        scanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> true);
        scanner.scan(path);

        /*AbstractBeanDefinition userMapper = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        userMapper.setBeanClass(MybatisFactoryBean.class);
        userMapper.getConstructorArgumentValues().addGenericArgumentValue(UserMapper.class);
        registry.registerBeanDefinition("userMapper", userMapper);

        AbstractBeanDefinition orderMapper = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        orderMapper.setBeanClass(MybatisFactoryBean.class);
        orderMapper.getConstructorArgumentValues().addGenericArgumentValue(OrderMapper.class);
        registry.registerBeanDefinition("orderMapper", orderMapper);*/
    }
}
